package com.blog.blog.service.impl;

import com.blog.blog.mapper.OssFileMapper;
import com.blog.blog.service.UploadService;
import com.blog.blog.service.oss.OssService;
import com.blog.blog.vo.OssFileVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class UploadServiceImpl implements UploadService {
    private final OssService ossService;
    private final OssFileMapper ossFileMapper;

    public UploadServiceImpl(OssService ossService, OssFileMapper ossFileMapper) {
        this.ossService = ossService;
        this.ossFileMapper = ossFileMapper;
    }

    @Override
    public OssFileVO upload(MultipartFile file) throws java.io.IOException {
        String original = file.getOriginalFilename();
        String ext = (original != null && original.contains(".")) ? original.substring(original.lastIndexOf('.')) : "";
        String objectKey = "uploads/" + java.time.LocalDate.now() + "/" + java.util.UUID.randomUUID().toString().replaceAll("-", "") + ext;
        byte[] bytes = file.getBytes();
        String contentType = file.getContentType();
        OssFileVO vo = ossService.upload(bytes, objectKey, contentType);
        // 落库（默认标记为使用中）
        ossFileMapper.insert(vo.getKey(), vo.getUrl());
        return vo;
    }
}


